import { createOrder } from '@/services/swagger/orderController';
import { Button, Col, message, Row, Space, Typography } from 'antd';
import React from 'react';

type UpdateOrderItemFn = (itemId: number, delta: number) => void;

interface OrderDetailsProps {
  orderItems: API.OrderDetailDTO[];
  onUpdateQuantity: UpdateOrderItemFn;
  setOrderItems: React.Dispatch<React.SetStateAction<API.OrderDetailDTO[]>>;
  dishMap: Record<number, any>; // 简化处理，也可以定义更具体的 Dish 类型
}

const { Text, Title } = Typography;

export const OrderDetails: React.FC<OrderDetailsProps> = ({
  orderItems,
  onUpdateQuantity,
  setOrderItems,
  dishMap,
}) => {
  // 下单函数
  const handlePlaceOrder = async () => {
    if (orderItems.length === 0) {
      message.warning('请先选择菜品');
      return;
    }

    const orderData: API.OrderFormDTO = {
      addressId: 1,
      paymentType: 1,
      details: [...orderItems],
    };

    try {
      const orderId = await createOrder(orderData);
      message.success(`下单成功，订单号：${orderId}`);
      setOrderItems([]);
    } catch (error) {
      message.error('下单失败，请重试');
      console.error(error);
    }
  };

  // 计算总价
  const calculateTotal = (items: API.OrderDetailDTO[]) => {
    return items.reduce((total, item) => {
      const dish = item.itemId ? dishMap[item.itemId] : undefined;
      const price = dish?.price || 0;
      return total + price * (item.num || 0);
    }, 0);
  };

  return (
    <div style={{ padding: '16px', backgroundColor: '#fff', borderRadius: '8px' }}>
      <Title level={4}>订单详情</Title>

      {orderItems.length === 0 ? (
        <Text type="secondary">暂无菜品</Text>
      ) : (
        <div>
          {orderItems.map((item) => {
            const dish = item.itemId ? dishMap[item.itemId] : undefined;

            return (
              <Row key={item.itemId || Math.random()} gutter={16} style={{ marginBottom: '16px' }}>
                <Col span={18}>
                  <Space>
                    <Text strong>{dish?.name || `菜品 #${item.itemId}`}</Text>
                    <Text type="secondary">({dish?.isVegetarian ? '素食' : '非素食'})</Text>
                  </Space>
                  <Space size="small">
                    <Button
                      size="small"
                      onClick={() => onUpdateQuantity(item.itemId!, -1)}
                      disabled={(item.num || 0) <= 0}
                    >
                      -
                    </Button>
                    <Text>{item.num || 0}X</Text>
                    <Button size="small" onClick={() => onUpdateQuantity(item.itemId!, 1)}>
                      +
                    </Button>
                  </Space>
                </Col>
                <Col span={6} style={{ textAlign: 'right' }}>
                  <Text>¥{(dish?.price ? dish.price * (item.num || 0) : 0).toFixed(2)}</Text>
                </Col>
              </Row>
            );
          })}
        </div>
      )}

      <Row style={{ borderTop: '1px solid #e8e8e8', paddingTop: '16px', marginTop: '16px' }}>
        <Col span={18}>
          <Space direction="vertical">
            <Text strong>小计:</Text>
            <Text strong>服务费 (5%):</Text>
            <Text strong style={{ fontSize: '18px' }}>
              总计:
            </Text>
          </Space>
        </Col>
        <Col span={6} style={{ textAlign: 'right' }}>
          <Space direction="vertical">
            <Text>¥{calculateTotal(orderItems).toFixed(2)}</Text>
            <Text>¥{(calculateTotal(orderItems) * 0.05).toFixed(2)}</Text>
            <Text style={{ fontSize: '18px' }}>
              ¥{(calculateTotal(orderItems) * 1.05).toFixed(2)}
            </Text>
          </Space>
        </Col>
      </Row>

      <Button
        type="primary"
        block
        style={{
          marginTop: '24px',
          backgroundColor: '#28a745',
          borderColor: '#28a745',
        }}
        onClick={handlePlaceOrder}
      >
        下单
      </Button>
    </div>
  );
};
